package com.tbvtc.agriculturalcreditchainserver2025.utils.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class CozeApiExample {
    private static final String API_TOKEN = "pat_rHA7xOyRmJaHm3dpqPpH8B1FBsli6YxhgRxN6jSxka3UYGtohc5li9MGNcPA1W6C";
    private static final String BOT_ID = "7502350088136785930";
    private static final String API_URL = "https://api.coze.cn/v3/chat";

    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();

        MediaType JSON = MediaType.parse("application/json");

        // 初始请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("bot_id", BOT_ID);
        requestBody.put("user_id", "123");
        requestBody.put("stream", false);
        requestBody.put("auto_save_history", true);

        JSONArray messages = new JSONArray();
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", "早上好");
        message.put("content_type", "text");
        messages.add(message);
        requestBody.put("additional_messages", messages);

        RequestBody body = RequestBody.create(requestBody.toJSONString(), JSON);

        // 轮询参数
        int maxRetries = 10; // 最大重试次数
        int retryInterval = 2000; // 轮询间隔(毫秒)
        JSONObject finalResponse = null;
        String conversationId = null;

        try {
            for (int i = 0; i < maxRetries; i++) {
                Request request = new Request.Builder()
                        .url(API_URL)
                        .addHeader("Authorization", "Bearer " + API_TOKEN)
                        .post(body)
                        .build();

                try (Response response = client.newCall(request).execute()) {
                    String responseBody = response.body().string();
                    JSONObject jsonResponse = JSONObject.parseObject(responseBody);

                    if (jsonResponse.getInteger("code") == 0) {
                        JSONObject data = jsonResponse.getJSONObject("data");
                        String status = data.getString("status");
                        conversationId = data.getString("conversation_id");

                        System.out.println("尝试 " + (i + 1) + ": 状态=" + status + ", 会话ID=" + conversationId);

                        if ("completed".equals(status)) {
                            finalResponse = jsonResponse;
                            break;
                        } else if ("in_progress".equals(status)) {
                            // 如果是进行中状态，继续轮询
                            System.out.println("处理中，等待后继续...");
                        } else {
                            System.err.println("未知状态: " + status);
                            break;
                        }
                    } else {
                        System.err.println("请求失败: " + jsonResponse.getString("msg"));
                        break;
                    }
                }

                // 如果不是最后一次尝试，等待后继续
                if (i < maxRetries - 1) {
                    Thread.sleep(retryInterval);

                    // 更新请求体中的conversation_id（如果已获取）
                    if (conversationId != null) {
                        requestBody.put("conversation_id", conversationId);
                        body = RequestBody.create(requestBody.toJSONString(), JSON);
                    }
                }
            }

            // 处理最终结果
            if (finalResponse != null) {
                System.out.println("=== 请求成功 ===");
                JSONObject data = finalResponse.getJSONObject("data");
                System.out.println("最终会话ID: " + data.getString("conversation_id"));

                // 解析回复内容
                JSONArray messagesArray = data.getJSONArray("messages");
                if (messagesArray != null && !messagesArray.isEmpty()) {
                    for (int i = 0; i < messagesArray.size(); i++) {
                        JSONObject msg = messagesArray.getJSONObject(i);
                        if ("assistant".equals(msg.getString("role"))) {
                            System.out.println("AI回复: " + msg.getString("content"));
                        }
                    }
                }

                System.out.println("完整响应: " + finalResponse.toJSONString());
            } else {
                System.err.println("请求未完成，已达到最大重试次数");
            }
        } catch (IOException | InterruptedException e) {
            System.err.println("请求异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
}